// use std::cmp;

struct Solution;

impl Solution {
    pub fn max_turbulence_size(a: Vec<i32>) -> i32 {
        if a.len() == 1 {
            return 1;
        }

        if a.len() == 2 {
            if a[0] == a[1] {
                return 1;
            }
            return 2;
        }

        let mut start = 0;
        // true表示 k-1 > k false表示 k-1 < k
        let mut sign = a[0] > a[1];
        // 长度
        let mut res = 0;

        for (index, val) in a.iter().skip(1).enumerate() {
            if sign && *val < a[index] {
                sign = false;
            } else if !sign && *val > a[index] {
                sign = true;
            } else {
                // 不符合要求
                // 1, 计算现在的长度
                let tmp = index - start + 1;
                // 2. 如果是目前最大的长度，更换
                if tmp > res {
                    res = tmp;
                }
                // 3. 更新start的值 这里如果出现相等，那么前一个就是非法的，必须抛弃
                if *val == a[index] {
                    start = index + 1;
                } else {
                    start = index;
                }
                // 4. 更新sign 这里计算的是下一次sign，所以是反的
                sign = a[index] < *val;
            }
        }

        let tmp = a.len() - start;
        if tmp > res {
            res = tmp;
        }

        res as i32
    }

    // pub fn max_turbulence_size(a: Vec<i32>) -> i32 {
    //     let mut inc = 1;
    //     let mut dec = 1;
    //     let mut res = 1;
    //
    //     for (index, val) in a.iter().skip(1).enumerate() {
    //
    //         if *val < a[index] {
    //             dec = inc + 1;
    //             inc = 1;
    //         } else if *val > a[index] {
    //             inc = dec + 1;
    //             dec = 1;
    //         } else {
    //             inc = 1;
    //             dec = 1;
    //         }
    //
    //         res = cmp::max(res, cmp::max(inc, dec));
    //     }
    //
    //     res
    // }
}


#[cfg(test)]
mod test {
    use crate::Solution;

    #[test]
    fn test_01() {
        let res = Solution::max_turbulence_size(vec![100]);
        assert_eq!(res, 1);
    }

    #[test]
    fn test_02() {
        let res = Solution::max_turbulence_size(vec![9, 4, 2, 10, 7, 8, 8, 1, 9]);
        assert_eq!(res, 5);
    }

    #[test]
    fn test_03() {
        let res = Solution::max_turbulence_size(vec![4, 8, 12, 16]);
        assert_eq!(res, 2);
    }

    #[test]
    fn test_04() {
        let res = Solution::max_turbulence_size(vec![2, 2, 2, 3]);
        assert_eq!(res, 2);
    }

    #[test]
    fn test_05() {
        let res = Solution::max_turbulence_size(vec![0, 8, 45, 88, 48, 68, 28, 55, 17, 24]);
        assert_eq!(res, 8);
    }
}

fn main() {
    let res = Solution::max_turbulence_size(vec![0, 8, 45, 88, 48, 68, 28, 55, 17, 24]);
    assert_eq!(res, 8);
}
